﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

/// <summary>
/// Summary description for Product
/// </summary>
[Serializable]
public class Product
{
    public int id                     {get;set;}
	public string product                {get;set;}
	public string productdesc            {get;set;}
	public int classification_id      {get;set;}
	public int freq_id                {get;set;}
	public string issn                   {get;set;}
	public int product_type_id        {get;set;}
	public int puplisher_id           {get;set;}
	public string auther1                {get;set;}
	public string auther2                {get;set;}
	public string topic                  {get;set;}
	public string publisher              {get;set;}
    public string dwoy { get; set; }
    public string lc { get; set; }
   public  List<ProductField> ProductFields { get; set; }
    public void importfromvalues(List<string> fields, System.Collections.ArrayList values)
    {
        int i = 0;
        foreach (string s in fields)
        {
            this.GetType().GetProperty(s).SetValue(this, values[i], null);
            i++;
        }
    }
    public void importfield(List<string> fields, System.Collections.ArrayList values)
    {
        int i = 0; 
        ProductField pf = new ProductField();
        foreach (string s in fields)
        {
           
            pf.GetType().GetProperty(s).SetValue(pf, values[i], null);
            i++;
        }
        if (ProductFields == null)
        {
            ProductFields = new List<ProductField>();
        }
        ProductFields.Add(pf);
    }
    public void importfield(string tag, string ind,  string subfield, string field)
    {
        ProductField pf = new ProductField();
        pf.tag = tag;
        pf.indicator = ind;
        pf.subfield = subfield;
        pf.field = field;
        if (ProductFields == null)
        {
            ProductFields = new List<ProductField>();
        }
        ProductFields.Add(pf);
    }
    public void getojectfrombytes(byte[] bytes)
    {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        System.IO.MemoryStream mss = new System.IO.MemoryStream(bytes);
        Product p = (Product)b.Deserialize(mss);
        System.Reflection.PropertyInfo[] pfarray = p.GetType().GetProperties();
        foreach (System.Reflection.PropertyInfo pf in pfarray)
        {
            this.GetType().GetProperty(pf.Name).SetValue(this, p.GetType().GetProperty(pf.Name).GetValue(p, null), null);
        }


    }

    public byte[] GetObjectbytes()
    {
        try
        {
            // create new memory stream
            System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream();

            // create new BinaryFormatter
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
                        = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            // Serializes an object, or graph of connected objects, to the given stream.
            _BinaryFormatter.Serialize(_MemoryStream, this);

            // convert stream to byte array and return
            return _MemoryStream.ToArray();
        }
        catch (Exception _Exception)
        {
            // Error
            Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
        }

        // Error occured, return null
        return null;
    }
    public void getfromdatabase(int id)
    {
        string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

        string selectString = "select * from Pendingobjects where id = @id";
        byte[] bytes = null;
        using (SqlConnection sqlConn = new SqlConnection(connString))
        {
            sqlConn.Open();

            using (SqlCommand sqlCmd = new SqlCommand(selectString, sqlConn))
            {
                sqlCmd.Parameters.AddWithValue("@id", id);
                SqlDataReader reader = sqlCmd.ExecuteReader();
                while (reader.Read())
                {
                    bytes = (byte[])reader["data"];
                }
            }
            sqlConn.Close();
        }
        if (bytes != null)
        {
            this.getojectfrombytes(bytes);
        }

    }
    public void setobjecttodatabase(string objectname, int companywhichadd, string usernamewhichadd)
    {
        string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        string InsertString = "Insert into pendingobjects (type,name,data,companyid,username) values (@type,@name,@data,@companyid,@username)";
        SqlConnection sqlConn = new SqlConnection(connString);
        SqlCommand command = sqlConn.CreateCommand();
        sqlConn.Open();
        command.CommandText = InsertString;
        command.CommandType = System.Data.CommandType.Text;
        command.Parameters.AddWithValue("@type", "product");
        command.Parameters.AddWithValue("@name", objectname);
        command.Parameters.AddWithValue("@data", GetObjectbytes());
        command.Parameters.AddWithValue("@companyid", companywhichadd);
        command.Parameters.AddWithValue("@username", usernamewhichadd);
        command.ExecuteNonQuery();
        sqlConn.Close();
    }
	public Product()
	{
		//
		// TODO: Add constructor logic here
		//
        this.ProductFields = new List<ProductField>();
	}
}

[Serializable]
public class ProductField
{
    public long  id             {get;set;}
    public string subfield      {get;set;}
    public string indicator { get; set; }
    public string field         {get;set;}
    public string tag           {get;set;}
    public long  product_id  {get;set;}
    public ProductField()
    {

    }

}